package ncov.dao.impl;

import ncov.dao.DepartmentDao;
import ncov.model.Department;
import org.hibernate.*;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.List;

@Repository
public class DepartmentDaoImpl implements DepartmentDao {
    @Autowired
    private SessionFactory sessionFactory;
    private Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    @Override
    public Department queryById(Integer deptId) {
        Session session = getSession();
        return session.get(Department.class, deptId);
    }

    @Override
    public Department queryByName(String name) {
        Session session = getSession();
        Query query = session.createQuery("FROM Department where deptName=?");
        query.setParameter(0, name);
        return (Department) query.uniqueResult();
    }

    @Override
    public List<Department> queryAllByLimit(int offset, int limit) {
        Query query = getSession().createQuery("from Department");
        query.setMaxResults(limit);
        query.setFirstResult(offset);
        List<Department> list = query.list();
        return list;
    }

    @Override
    public List<Department> queryAll(Department department) {
        Session session = getSession();
        Criteria criteria = session.createCriteria(Department.class)
                .add(Restrictions.like("deptName", department.getDeptName()));
        return criteria.list();
    }

    @Override
    public int insert(Department department) {
        Session session = null;
        try{
        session = getSession();
        Transaction tx = session.beginTransaction();
        Serializable save = session.save(department);
        System.out.println(save);
        tx.commit();
        }
        catch (Exception e) {
            e.printStackTrace();
            session.getTransaction().rollback();
        } finally{
            session.close();}
        return 0;
    }

    @Override
    public int update(Department department) {
        Session session = getSession();
        session.update(department);
        return 0;
    }

    @Override
    public int deleteById(Integer deptId) {
        Session session = null;
        try{
        session = getSession();
        session.beginTransaction();
        Department department = new Department();
        department.setDeptId(deptId);
        session.delete(department);
        session.getTransaction().commit();}
        catch (Exception e) {
            e.printStackTrace();
            session.getTransaction().rollback();
        } finally{
        session.close();}
        return 0;
    }
}
